package cn.kjcoder.redis.controller;

import cn.kjcoder.redis.domain.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hkj
 * @email 1349091387@qq.com
 * @date 2022/1/19
 * 源码允许修改，并且本人十分乐意有 大佬 来对代码进行 随 意 调 教
 **/
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 创建商品，并存入redis中
     * @param product
     */
    @PostMapping("/create")
    public void create(Product product){
        //TODO 创建商品，并存入mysql中（省略）

        //将商品存入redis中
        String key = "product:" + 100;
        //将product对象里面的属性和值转化成Map对象
        Map<String, Object> map=this.objectToMap(product);
        //批量将所有键值对添加到redis
        this.redisTemplate.opsForHash().putAll(key,map);

        Object name = this.redisTemplate.opsForHash().get(key, "name");
        log.info("name={}",name);

        Object price = this.redisTemplate.opsForHash().get(key, "price");
        log.info("price={}",price);

        Object detail = this.redisTemplate.opsForHash().get(key, "detail");
        log.info("detail={}",detail);
    }

    /**
     * 商品价格上涨
     */
    @PostMapping("/addPrice")
    public void addPrice(Long id,Integer price){
        String key = "product:" + 100;
        //对指定的field添加对应的值
        this.redisTemplate.opsForHash().increment(key,"price",price);
        Object prices = this.redisTemplate.opsForHash().get(key, "price");
        log.info("prices={}",prices);
    }

    /**
     * 将对象里面的属性和值转化成Map对象
     */
    public  Map<String, Object> objectToMap(Object obj)  {
        Map<String, Object> map = new HashMap<String,Object>();
        Class<?> clazz = obj.getClass();
        //遍历所有属性
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = null;
            try {
                value = field.get(obj);
            } catch (IllegalAccessException e) {
                log.error(e.getMessage());
            }
            map.put(fieldName, value);
        }
        return map;
    }
}
